package com.ben.utils.device

import com.ben.utils.log.Logger

/**
 * @author bin.yang
 * @date 2019/3/20
 * maintainer bin.yang
 * copyright 2019 Inc. All rights reserved.
 * desc:
 */
object ProductUtils {

    /**
     * 获取环境变量
     */
    fun getProp(key: String?, default: String? = null): String? {
        if (key.isNullOrEmpty()) {
            return default
        }
        return try {
            val getStringMethod = Class.forName("android.os.SystemProperties")
                .getMethod("get", String::class.java, String::class.java)
            return when (val s: Any? = getStringMethod.invoke(null, key, default)) {
                is String -> if (s.isEmpty()) default else s
                null -> default
                else -> (getStringMethod.invoke(null, key, default) as String).toString()
            }
        } catch (e: Exception) {
            default
        } catch (t: Throwable) {
            default
        }
    }

    /**
     * 设置环境变量
     */
    fun setProp(key: String?, default: String? = null) {
        if (key.isNullOrEmpty()) {
            Logger.e("setProp", "key is empty")
            return
        }
        try {
            val getStringMethod = Class.forName("android.os.SystemProperties")
                .getMethod("set", String::class.java, String::class.java)
            getStringMethod.invoke(null, key, default)
        } catch (e: Exception) {
            e.printStackTrace()
        } catch (t: Throwable) {
            t.printStackTrace()
        }
    }
}
